<?php
/**
 * Integracja z płatnościami internetowymi platnosci.pl {@link https://www.platnosci.pl}
 * 
 * @version $Id$
 * @author Gabriel Habryn, widmogrod@gmail.com
 * @license MIT License
 */
class Payments_PlatnosciController extends Promotor_Controller_Action
{
	public $skin = array(
		// layout
		'layout' => 'payments_platnosci',
	);
	
	/**
	 * @var Zend_Config
	 */
	public $config;
	
	/**
	 * @var KontorX_Payments_Platnosci
	 */
	public $payments;

	public function init()
	{
		$this->config = $this->_helper->config('config.ini');
		$this->payments = new KontorX_Payments_Platnosci($this->config);
	}

	/**
	 * @return void
	 */
	public function indexAction()
	{
		$cart = Shop_Model_Cart::getInstance();
		
		$rq = $this->getRequest();

		// tylko gdy płatności sa aktywne
		$paymentsActive = (bool) $this->_helper->config->config('config.ini','shop')->payments->isActive;
		$this->_helper->redirectUntil->goToSimpleUntil($paymentsActive,'success','checkout', 'shop');
		
		
		// tylko gdy uzytkownik wypełnił dane
		$userData = $cart->getUserData();
		$this->_helper->redirectUntil->gotoRouteUntil($userData, array(),'shop-checkout');
		
		@list ($firstname, $lastname) = explode(' ',trim($userData['fullname']));

		$desc = sprintf('Płatności za zakupy internetowe nr %s%s%s/%s', 
							date('Y'), date('m'), date('d'), $userData['orderId']);

		$this->payments->setSessionId($userData['session_id']);
		$this->payments->setAmount($userData['amount'], false);
		$this->payments->setDesc($desc);
		$this->payments->setFirstName($firstname);
		$this->payments->setStreet($userData['address']);
		$this->payments->setPostCode($userData['postcode']);
		$this->payments->setCity($userData['city']);
		$this->payments->setLastName($lastname);
		$this->payments->setEmail($userData['email']);
		
//		$this->payments->set

		$this->view->form = new Payments_Form_Platnosci(array(
			'payments' => $this->payments
		));
		
		//$this->getHelper('Redirector')->goToSimple('index','checkout');
	}

	/**
	 * Płatność została dokonana.
	 * wyświetlana jest informacja użytkownikowi
	 * 
	 * @return void
	 */
	public function pozytywnyAction()
	{
		/* @var $flashMessanger Zend_Controller_Action_Helper_FlashMessenger */
		$flashMessanger = $this->_helper->getHelper('flashMessenger');

		Zend_Session::regenerateId();

		/* @var $rq Zend_Controller_Request_Http */
		$rq = $this->getRequest();
		
		// dane zwracane z płatności
		$query = $rq->getQuery();
		
		$sessionId = $this->_getParam('sessionId', $this->_getParam('session_id'));
		$model = new Shop_Model_Order();
		$row = $model->updateStatusSuccess($sessionId);
		$this->view->row = $row;

		// dodawanie wiadomości z modelu @todo dodać do logowania
		array_map(array($flashMessanger, 'addMessage'), $model->getMessages(true));
		
		if ($model->getStatus() === Shop_Model_Order::SUCCESS)
		{
			$orderId = $this->_getParam('orderId', $this->_getParam('order_id'));
			if (!is_numeric($orderId))
			{
				$orderId = $row->id;
			}
			
			$time = strtotime($row->date);
			$subject = sprintf('Zamówienie [%s%s%s/%s] - opłata dokonana', date('Y', $time), date('m', $time), date('d', $time), $orderId);
			$this->view->subject = $subject;
			
			$html = $this->view->render('platnosci/send-mail.phtml');
			$config = $this->_helper->config('checkout.ini', 'shop');

			// wysyłanie maila
			$model = new Default_Model_Mail();
			$model->setConfig($config->zamowienie);

			// TODO: dodać mail użytkownika
			$model->getMail()->addTo($row->email);
			
			$model->setSubject($subject);
			$model->send(null, $html);

			// dodawanie wiadomości z modelu @todo dodać do logowania
			array_map(array($flashMessanger, 'addMessage'), $model->getMessages(true));
		}
		
		if (Zend_Session::isStarted())
		{
			Zend_Session::regenerateId();
		}
	}

	/**
	 * Wystąpiły błędy podczas dokonywania płatności.
	 * Wyświetlana jest informacja użytkownikowi
	 * 
	 * @return void
	 */
	public function negatywnyAction()
	{
		/* @var $rq Zend_Controller_Request_Http */
		$rq = $this->getRequest();

		// dane zwracane z płatności
		$query = $rq->getQuery();

		// przetworzenie odpowiedzi z platnosci.pl 
		$respond = new KontorX_Payments_Platnosci_Respond($query);

		// pobieranie kodu błędu
		$this->view->message = $this->payments->getErrorByCode($respond->getError());

		$sessionId = $this->_getParam('sessionId', $this->_getParam('session_id'));
		$model = new Shop_Model_Order();
		$row = $model->updateStatusSuccess($sessionId);
		$this->view->row = $row;

		// pobieranie kodu błędu
		$this->view->message = $this->payments->getErrorByCode($respond->getError());
		
		if ($model->getStatus() === Shop_Model_Order::SUCCESS)
		{
			$orderId = $this->_getParam('orderId', $this->_getParam('order_id'));
			if (!is_numeric($orderId))
			{
				$orderId = $row->id;
			}

			$time = strtotime($row->date);
			$subject = sprintf('Zamówienie [%s%s%s/%s] - opłata NIE dokonana!', date('Y', $time), date('m', $time), date('d', $time), $orderId);
			$this->view->subject = $subject;
			
			$html = $this->view->render('platnosci/send-fail-mail.phtml');
			$config = $this->_helper->config('checkout.ini', 'shop');

			// wysyłanie maila
			$model = new Default_Model_Mail();
			$model->setConfig($config->zamowienie);

//			// TODO: dodać mail użytkownika
			$model->getMail()->addTo($row->email);
			
			$model->setSubject($subject);
			$model->send(null, $html);

			// dodawanie wiadomości z modelu @todo dodać do logowania
			array_map(array($flashMessanger, 'addMessage'), $model->getMessages(true));
		}
		
		if (Zend_Session::isStarted())
		{
			Zend_Session::regenerateId();
		}
	}
	
	/**
	 * @return void
	 */
	public function onlineAction()
	{
		$log = Zend_Registry::get('Zend_Log');
		$log->log('onlineAction', Zend_Log::CRIT);
		$log->log(print_r($_GET, true) . "\n\n\n" . print_r($_POST, true), Zend_Log::CRIT);

		/* @var $viewRenderer Zend_Controller_Action_Helper_ViewRenderer */
		$viewRenderer = $this->getHelper('ViewRenderer');
		$viewRenderer->setNoRender(true);
		
		/* @var $layout Zend_Layout_Controller_Action_Helper_Layout */
		$layout = $this->getHelper('Layout');
		$layout->disableLayout();

		/* @var $rq Zend_Controller_Request_Http */
		$rq = $this->getRequest();

		if (!$rq->isPost())
		{
			// nie są to dane post więc exit
			$log->log('onlineAction - nie przekazano danych POST', Zend_Log::CRIT);
			die('OK');
		}

		// dane zwracane z płatności
		$post = $rq->getPost();

		try {
			// przetworzenie odpowiedzi z platnosci.pl 
			$respond = new KontorX_Payments_Platnosci_Response_Online($post);
		} catch(Exception $e) {
			$log->log($e->getMessage(), Zend_Log::CRIT);
			$log->log('onlineAction - wystąpił bład podczas dobierania statusu', Zend_Log::CRIT);
			die('OK');
		}

//		// TODO: Przesłać do notification
//		$model = new Shop_Model_Order();
//		$model->updateStatus($respond);

		// Powiadomienie o odebraniu wiadomości
		die('OK');
	}
}